<?php

namespace App\Http\Controllers\Dashboard;


use App\Http\Controllers\Common\Internal;
use App\Models\CityTicket;
use App\Models\LoanApplication;
use App\Models\LoanTypeList;
use App\Models\YqArea;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;


class AppSettingController extends BaseController
{
    /**
     * @param Request $request
     * @param $key
     * @return JsonResponse
     */
    public function get(Request $request, $key) {
        return response()->json([
            'msg' => "ok",
            'code' => 0,
            'data' => app_setting($key),
        ]);
    }

    /**
     * @param Request $request
     * @param $key
     * @return JsonResponse
     */
    public function save(Request $request, $key) {
        if (app_setting([$key => $request->value])) {
            return response()->json([
                'msg' => "ok",
                'code' => 0,
                'data' => app_setting($key),
            ]);
        } else {
            return response()->json([
                'msg' => "ok",
                'code' => 0,
                'data' => null,
            ]);
        }
    }

    public function saveTicket(Request $request)
    {
        $all = $request->all();


        $addedTags = $all['addedTags'];
        $defaultTags = $all['defaultTags'];

        $city_list = [];
        //城市标签
        foreach ($addedTags as $value) {
             if (strpos($value['name'], '省') !== false) {
                 $citys = self::getCitys($value['name'],$value['price'],$value['spec']) ;
                 $city_list = array_merge($city_list, $citys);
             }elseif (strpos($value['name'],'市') !== false){
                 $city_list[] = [
                     'city' => preg_replace("/市$/", "", $value['name']),
                     'type'=>$value['spec'],
                     'ticket'=>$value['price'],
                 ];
             }else{
                 $city_list[] = [
                     'city' => $value['name'],
                     'type'=>$value['spec'],
                     'ticket'=>$value['price'],
                 ];
             }
        }
        //默认标签
        foreach ($defaultTags as $value) {
            $city_list[] = [
                'city' => '默认',
                'type'=>$value['spec'],
                'ticket'=>$value['price']
            ];
        }

        DB::statement('TRUNCATE TABLE city_ticket');
        CityTicket::insert($city_list);
        return response()->json([
            'msg' => "ok",
            'code' => 0,
            'data' => null,
        ]);
    }

    public function getTicket()
    {
        $defaultTags = [];
        //默认数据
        $loan_type_list = LoanTypeList::get()->toArray();
        foreach ($loan_type_list as $value){
            $whereData = [
                'city'=>'默认',
                'type'=>$value['loan_type']
            ];
            $defaultTag = CityTicket::where($whereData)->first();
            $data = [];
            $data['name'] = '默认';
            $data['spec'] = $value['loan_type'];
            $data['id'] = $value['id'];
            $data['price'] = 0;
            if($defaultTag){
                $data['price'] = $defaultTag->ticket;
            }
            $defaultTags[] = $data;
        }
        $tags = [];
        $lists = CityTicket::where('city','!=','默认')->get()->toArray();
        foreach ($lists as $key => $value) {
            $tags[$key]['id'] = $value['id'];
            $tags[$key]['name'] = strlen($value['city'])>4?$value['city'].'市':$value['city'];
            $tags[$key]['spec'] = $value['type'];
            $tags[$key]['price'] = $value['ticket'];
        }

        $tagIdCounter = CityTicket::orderBy('id','desc')->pluck('id');
        $tagIdCounter = $tagIdCounter?$tagIdCounter->first():1;
        return response()->json([
            'msg' => "ok",
            'code' => 0,
            'data' => [
                'tagIdCounter' => $tagIdCounter,
                'defaultTags' => $defaultTags,
                'addedTags' => $tags
            ],
        ]);

    }



    public function getCitys($address_name,$price,$spec)
    {
        $address_code = YqArea::where(['address_name'=>$address_name])->pluck('address_code');
        $address = YqArea::where(['parent_code'=>$address_code])->get()->toArray();
        foreach ($address as $k=>$v){
            $city[] =   [
                'city'=>str_replace("市", "", $v['address_name']),
                'type'=>$spec,
                'ticket'=>$price,
            ];
        }
        return $city;
    }


    public function dataStatistics(Request $request)
    {
        $data = $request->all();
        $dateRange = $data['dateRange'];

        $startTime = date('Y-m-d',time()).' 00:00:00';
        $endTime =date('Y-m-d',time()).' 23:59:59';
        if($dateRange){
            $startTime = $dateRange[0].' 00:00:00';
            $endTime =$dateRange[1].' 23:59:59';
        }
        $usersPerDay = DB::table('loan_application')
            ->where('apply_at','>=',$startTime)
            ->where('apply_at','<=',$endTime)
            ->where('user_id','!=',0)
            ->select(
                DB::raw('DATE(apply_at) as date'), // 转换日期
                DB::raw('COUNT(*) as count') // 计数
            )
            ->groupBy('date') // 按日期分组
            ->orderBy('date','desc')
            ->get()
            ->toArray();
        $data = [];
        foreach ($usersPerDay as $summary) {
            $re = [];
            $re['date'] = $summary->date;
            $re['ordersTaken'] = $summary->count;
            $orders = LoanApplication::whereBetween('apply_at', [
                $summary->date . ' 00:00:00',
                $summary->date . ' 23:59:59'
            ])
            ->where('user_id','!=',0)
            ->get();
            $sum = 0;
            // 遍历订单详情
            foreach ($orders as $loan) {
                $loan['need_ticket'] = Internal::getNeedTicket($loan->category_type, $loan->province,$loan->id);
                $sum += $loan['need_ticket'];
                $re['list'][] = $loan;
            }
            $re['goldSpent'] = $sum;
            $data[] = $re;
        }
        return response()->json([
            'msg' => "ok",
            'code' => 0,
            'data' => $data
        ]);

    }




}
